﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using System.Threading;


namespace EstevesRecordersProject
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        //
        public List<StatisticEnum> selectedStatistics = null;
        public TimeSpan wtlt = new TimeSpan(0, 0, 10);
        public TimeSpan itlt = new TimeSpan(0, 0, 10);

        public List<StatisticEnum> SelectedStatistics { get { return selectedStatistics; } set { selectedStatistics = value;}}
        public TimeSpan Wtlt { get { return wtlt; } set { wtlt = value; } }
        public TimeSpan Itlt { get { return itlt; } set { itlt = value; } }
        //
        private List<Recorder> selectedRecorders = null;

        public MainWindow()
        {
            try
            {
                InitializeComponent();
                MakeGridRecorders();

                CultureInfo ci = new CultureInfo("en-GB");
                Thread.CurrentThread.CurrentCulture = ci;
                Thread.CurrentThread.CurrentUICulture = ci;

                lblMessage.Content = "";

                //initialize stat list
                selectedStatistics = new List<StatisticEnum>();
                foreach(StatisticEnum s in Enum.GetValues( typeof(StatisticEnum) ))
                {
                    selectedStatistics.Add(s);
                }
            }
            catch (Exception ex)
            {
                lblMessage.Content = ex.Message;
                lblMessage.Foreground = Brushes.Red;
            }
        }

        private void MenuItem_ClickAddNewRecord(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowAddNewRecorder window = new WindowAddNewRecorder();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickEditRecord(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowEditRecorder window = new WindowEditRecorder();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickLoadFile(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowLoadFile window = new WindowLoadFile();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickConnectionString(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowConnectionString window = new WindowConnectionString();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickStatisticsOptions(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowStatistics window = new WindowStatistics(this);
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickDeletePerformance(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowDeletePerformance window = new WindowDeletePerformance();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickCheckLoadedDate(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;

            WindowsLoadedDate window = new WindowsLoadedDate();
            window.Show();

            this.Cursor = Cursors.Arrow;
        }

        private void MenuItem_ClickSplitToSingleOptions(object sender, RoutedEventArgs e)
        {

        }

        //------------------------
        private void MakeGridRecorders()
        {
            gridRecorders.Children.Clear();

            List<Recorder> recorderList =  Repository.GetAllRecorders();

            int r = (int)((this.Width) / 250);
            if (r == 0) r = 1;

            int c = 1;
            if (recorderList.Count % r == 0)
            {
                c = (int)(recorderList.Count / r);
            }
            else
            {
                c = (int)(recorderList.Count / r) + 1;
            }

            if (c == 0 && recorderList.Count != 0) c = 1;

            int x = 0;
            int y = 0;

            int i = -1;
            int j = 0;
            int k = 0;

            foreach (Recorder rec in recorderList)
            {
                i++;
                j++; 

                if ((i  % r) == 0)
                {
                    k ++;
                    j = 0;
                }

                CheckBox ch = new CheckBox();
                ch.Name = "cb" + rec.id;
                ch.Content = rec.ToString();
                ch.Margin = new Thickness(250 * j, 10 + (k - 1) * 30, 0, 0);

                gridRecorders.Children.Add(ch);
            }

            groupBoxRecorders.Height = (40 * c + 20);
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            try
            {
                MakeGridRecorders();

                gridStatistics.Margin = new Thickness(gridStatistics.Margin.Left, 65 + groupBoxRecorders.Height, gridStatistics.Margin.Right, gridStatistics.Margin.Bottom);
            }
            catch (Exception ex)
            {
                lblMessage.Content = ex.Message;
                lblMessage.Foreground = Brushes.Red;
            }
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                lblMessage.Content = "";

                List<Row> source = new List<Row>();
                List<Row> groupSource = new List<Row>();
                selectedRecorders = SelectedRecorders();
                DateTime? dateTimeStartTemp = datePickerFrom.SelectedDate;
                DateTime? dateTimeStopTemp = datePickerTo.SelectedDate;

                if (dateTimeStartTemp == null) throw new ApplicationException("Start time have to be choosen.");
                if (dateTimeStopTemp == null) throw new ApplicationException("End time have to be choosen.");
                if (dateTimeStopTemp < dateTimeStartTemp) throw new ApplicationException("Start time have to be lower than end time.");

                DateTime dateTimeStart = new DateTime(
                    dateTimeStartTemp.Value.Year,
                    dateTimeStartTemp.Value.Month,
                    dateTimeStartTemp.Value.Day,
                    dateTimeStartTemp.Value.Hour,
                    dateTimeStartTemp.Value.Minute,
                    dateTimeStartTemp.Value.Second);

                DateTime dateTimeStop = new DateTime(
                    dateTimeStopTemp.Value.Year,
                    dateTimeStopTemp.Value.Month,
                    dateTimeStopTemp.Value.Day,
                    dateTimeStopTemp.Value.Hour,
                    dateTimeStopTemp.Value.Minute,
                    dateTimeStopTemp.Value.Second);

                foreach (Recorder r in selectedRecorders)
                {
                    for (int i = 0; i < r.NrOfLines; i++)
                    {
                        Line l = r.Line(i + 1);


                        String longerThan = wtlt.TotalSeconds + "s";
                        String longerThan2 = itlt.TotalSeconds + "s";

                        foreach (StatisticEnum s in selectedStatistics)
                        {
                            MyTimeSpan mts = new MyTimeSpan();
                            String name = "";

                            switch (s)
                            {
                                case StatisticEnum.WorkTime:
                                    mts = Statistics.GetWorktime(l, dateTimeStart, dateTimeStop);
                                    name = "Whole worktime";
                                    break;
                                case StatisticEnum.IdleTime:
                                    mts = Statistics.GetIdleTime(l, dateTimeStart, dateTimeStop);
                                    name = "Whole idle time";
                                    break;
                                case StatisticEnum.WorkTimeLongerThan:
                                    mts = Statistics.GetWorktTimeLongerThan(l, dateTimeStart, dateTimeStop, wtlt);
                                    name = "Whole worktime time (longar than " + longerThan + ")";
                                    break;
                                case StatisticEnum.IdleTimeLongerThan:
                                    mts = Statistics.GetIdleTimeLongerThan(l, dateTimeStart, dateTimeStop, itlt);
                                    name = "Whole idle time time (longar than " + longerThan2 + ")";
                                    break;
                                default:
                                    throw new ApplicationException("Statistic unnown!");

                            }

                            Row row = new Row();
                            row.Recorder = r.ToString() + "\t"; ;
                            row.Line = l.name + "( nr: " + l.nr + ")" + "\t";
                            row.Name = name + ":" + "\t";
                            row.Statistics = mts.TimeSpan.ToString() + "\t";
                            row.Info = mts.Info + "\t";
                            row.Count = mts.count + "\t";
                            source.Add(row);

                        }
                    }
                }

                dataGrid1.ItemsSource = source;

                //Grouping Grid
                MyTimeSpan mtsGroup = new MyTimeSpan();
                
                mtsGroup = Statistics.GetWorktimeGroup(selectedRecorders, dateTimeStart, dateTimeStop);
                Row worktimeGroupRow = new Row();
                worktimeGroupRow.Name = "Whole worktime";
                worktimeGroupRow.Statistics = mtsGroup.TimeSpan.ToString();
                worktimeGroupRow.Info = mtsGroup.Info;
                worktimeGroupRow.Count = mtsGroup.count.ToString();
                groupSource.Add(worktimeGroupRow);

                mtsGroup = Statistics.GetIdleTimeGroup(selectedRecorders, dateTimeStart, dateTimeStop);
                Row idleTimeGroupRow = new Row();
                idleTimeGroupRow.Name = "Whole idle time";
                idleTimeGroupRow.Statistics = mtsGroup.TimeSpan.ToString();
                idleTimeGroupRow.Info = mtsGroup.Info;
                idleTimeGroupRow.Count = mtsGroup.count.ToString();
                groupSource.Add(idleTimeGroupRow);

                mtsGroup = Statistics.GetWorktimeGroupOR(selectedRecorders, dateTimeStart, dateTimeStop);
                Row worktimeGroupORRow = new Row();
                worktimeGroupORRow.Name = "Whole worktime (Logical OR)";
                worktimeGroupORRow.Statistics = mtsGroup.TimeSpan.ToString();
                worktimeGroupORRow.Info = mtsGroup.Info;
                worktimeGroupORRow.Count = mtsGroup.count.ToString();
                groupSource.Add(worktimeGroupORRow);

                mtsGroup = Statistics.GetIdleTimeGroupOR(selectedRecorders, dateTimeStart, dateTimeStop);
                Row idleTimeGroupANDRow = new Row();
                idleTimeGroupANDRow.Name = "Whole idle time (Logical AND)";
                idleTimeGroupANDRow.Statistics = mtsGroup.TimeSpan.ToString();
                idleTimeGroupANDRow.Info = mtsGroup.Info;
                idleTimeGroupANDRow.Count = mtsGroup.count.ToString();
                groupSource.Add(idleTimeGroupANDRow);

                dataGrid2.ItemsSource = groupSource;
                
                
            }
            catch (Exception ex)
            {
                lblMessage.Content = ex.Message;
                lblMessage.Foreground = Brushes.Red;
                this.Cursor = Cursors.Arrow;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// select all recorders
        /// </summary>
        /// <returns></returns>
        private List<Recorder> SelectedRecorders()
        {
            List<Recorder> rList = new List<Recorder>();

            foreach (Control c in gridRecorders.Children)
            {
                if (c is CheckBox)
                {
                    CheckBox ch = (CheckBox)c;

                    if (ch.IsChecked == true)
                    {
                        int rId = Int32.Parse(ch.Name.Substring(2));
                        Recorder r = Repository.GetRecorderById(rId);

                        rList.Add(r);
                    }
                }
            }

            return rList;
        }

        private void btnToExcel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                lblMessage.Content = "";

                selectedRecorders = SelectedRecorders();
                DateTime? dateTimeStartTemp = datePickerFrom.SelectedDate;
                DateTime? dateTimeStopTemp = datePickerTo.SelectedDate;

                if (dateTimeStartTemp == null) throw new ApplicationException("Start time have to be choosen.");
                if (dateTimeStopTemp == null) throw new ApplicationException("End time have to be choosen.");
                if (dateTimeStopTemp < dateTimeStartTemp) throw new ApplicationException("Start time have to be lower than end time.");

                DateTime dateTimeStart = new DateTime(
                    dateTimeStartTemp.Value.Year,
                    dateTimeStartTemp.Value.Month,
                    dateTimeStartTemp.Value.Day,
                    dateTimeStartTemp.Value.Hour,
                    dateTimeStartTemp.Value.Minute,
                    dateTimeStartTemp.Value.Second);

                DateTime dateTimeStop = new DateTime(
                    dateTimeStopTemp.Value.Year,
                    dateTimeStopTemp.Value.Month,
                    dateTimeStopTemp.Value.Day,
                    dateTimeStopTemp.Value.Hour,
                    dateTimeStopTemp.Value.Minute,
                    dateTimeStopTemp.Value.Second);

                WriteToExcel(dateTimeStart, dateTimeStop);
            }
            catch (Exception ex)
            {
                lblMessage.Foreground = Brushes.Red;
                lblMessage.Content = ex.Message;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// write to excel
        /// </summary>
        private void WriteToExcel(DateTime dateStart, DateTime dateStop)
        {

            List<Recorder> selectedRecorders = SelectedRecorders();

            //make an excel file
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null) throw new Exception("EXCEL could not be started. Check that your office installation and project references are correct.");

            Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
            object misValue = System.Reflection.Missing.Value;

            if (ws == null) throw new Exception("Worksheet could not be created. Check that your office installation and project references are correct.");

            xlApp.Visible = true;

            //dla kazdego rejestratora
            int x = 0;
            int y = 0;

            y++;
            ws.Cells[y, 1] = "From: " + dateStart.ToLongDateString();

            y++;
            ws.Cells[y, 1] = "To: " + dateStop.ToLongDateString();

            y++;
            foreach (Recorder r in selectedRecorders)
            {
                y++;
                ws.Cells[y,1] = r.ToString();
                y++;

                ws.Cells[y,1] = "#";
                ws.Cells[y,2] = "Date";
                ws.Cells[y,3] = "Time";
                x = 3;

                //dla kazdej linii
                foreach (Line l in r.Lines)
                {
                    x++;
                    ws.Cells[y, x] = l.nr + ". " + l.name;
                }

                List<Performance> performanceList = Repository.GetRecorderPerformanceInTime(r, dateStart, dateStop);
                performanceList.OrderBy(p => p.date);

                //performance

                for (int i = 0; i < performanceList.Count; i++)
                {
                    y++;

                    Performance p = performanceList[i];

                    ws.Cells[y, 1] = i + 1;
                    ws.Cells[y, 2] = p.date.ToShortDateString();
                    ws.Cells[y, 3] = p.date.ToLongTimeString();

                    ws.Cells[y, 3 + Int32.Parse( Repository.GetLine( p.idLinel).nr)] = p.value;
                }

                y++;
            }

            xlApp.Visible = true;
            //xlApp.Quit();

        }

        
    }
}
